<template>
  <view>
    <u-popup mode="center" round="5rpx" :show="show" @close="close" @open="open">
      <slot>
        <view class="popup-content">
          <text class="title">{{ config.title }}</text>
          <slot name="content" :result="config">
            <view class="modal" v-if="config.type == 'modal'">
              <text>{{ config.content }}</text>
            </view>
            <view class="textarea" v-else>
              <u-textarea v-model="config.content" placeholder="请输入内容" count custom-class="x-txt"></u-textarea>
            </view>
          </slot>
          <view class="btns">
            <view class="btns-item">
              <u-button @click="emits('cancel'), close('cancel')" size="large">{{ config.cancelText }}</u-button>
            </view>
            <view class="btns-item">
              <u-button @click="confirm" type="primary" size="large">{{ config.confirmText }}</u-button>
            </view>
          </view>
        </view>
      </slot>
    </u-popup>
  </view>
</template>
<script setup>
import { reactive, ref } from "vue";

const config = ref({
  title: "标题",
  placeholder: "请输入内容",
  confirmText: "确定",
  cancelText: "取消",
  content: "",
  type: "input", // input 输入框 modal
});

const show = ref(false);
const open = (data) => {
  if (data) {
    // APP 端输入框 v-module 绑定的值不能为null，否则会报错
    if (!data.content) data.content = "";
    config.value = { ...data };
  }
  show.value = true;
};
const close = (type) => {
  show.value = false;

  // 如果有自定义的关闭事件，则执行关闭事件
  if (config.value.onClose && typeof config.value.onClose === "function" && type == "cancel") {
    try {
      config.value.onClose();
    } catch (error) {
      console.log("onClose error", error);
    }
  }

};

const confirm = () => {
  emits("confirm", config.value)
  close();
  if (config.value.onConfirm && typeof config.value.onConfirm === "function") {
    try {
      config.value.onConfirm(config.value);
    } catch (error) {
      console.error("onConfirm error", error);
    }
  }
};

defineExpose({ open, close });

const emits = defineEmits(["confirm", "cancel"]);
</script>

<style scoped lang="scss">
.popup-content {
  padding: 20rpx;
  width: 260rpx;
  max-width: 80vw;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  .title {
    font-weight: bold;
  }

  .content {
    text-align: center;
    margin-top: 10rpx;
    max-height: 50vh;
    max-width: 100%;
    overflow: scroll;
  }

  .textarea {
    width: 80%;
    margin: 10rpx 0rpx;

    ::v-deep .u-textarea__field {
      font-size: 13rpx;
    }
  }

  .modal {
    width: 80%;
    margin: 10rpx 0rpx;
    text-align: center;
  }

  .btns {
    display: flex;
    width: fit-content;
    justify-content: space-between;
    margin-top: 20rpx;

    .btns-item {
      margin: 0rpx 15rpx;

      ::v-deep .u-button {
        padding: 2rpx 20rpx;
      }
    }
  }
}
</style>
